package production.practice.common.interceptor;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import production.practice.pojo.entity.User;
import production.practice.pojo.fuction.authorization.TokenProperties;
import production.practice.utils.BinaryUtils;
import production.practice.utils.RedisUtil;
import production.practice.utils.SysUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器,拦截所有请求,获取当前登录的个人信息,并完成token的时间刷新
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisUtil redisUtil;
    @Resource
    TokenProperties tokenProperties;



    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //检测是否有请求头令牌
        String token = request.getHeader(tokenProperties.getTokenName());

        //如果没有请求头令牌,则检测请求参数中是否有令牌
        if(BinaryUtils.isEmpty(token)){
            token=request.getParameter(tokenProperties.getTokenName());
        }

        //对token进性处理
        if (!SysUtil.checkToken(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未登录\"}");
            return false;
        }
        //获得处理后的token
        token=SysUtil.deCodeToken(token);

        //判断redis中是否有token,并根据token拿到用户的信息
        Object object = redisUtil.get(token);

        if(null!=object && object instanceof User){
            User user = (User) object;
            //刷新token的过期时间
            redisUtil.expire(token,tokenProperties.getExpire());
            SysUtil.setCurrentUser(user);
            //将用户信息放入到ThreadLocal中
            return true;
        }else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未登录\"}");
            return false;
        }

    }
}
